//
//  DFChannelDAO.m
//  doubanFun
//
//  Created by bing on 16/3/27.
//  Copyright © 2016年 bing. All rights reserved.
//  模型数据层

#import "DFChannelDAO.h"
#import <FMDB/FMDB.h>
#import <sqlite3.h>

@interface DFChannelDAO ()
@property (nonatomic, strong) FMDatabaseQueue *queue;
@end

@implementation DFChannelDAO

+ (instancetype)sharedDAO {
    static DFChannelDAO *dao;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dao = [[DFChannelDAO alloc] init];
        NSString *docDir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        docDir = [docDir stringByAppendingPathComponent:@"mydb.sqlite3"];
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:docDir];
        dao.queue = [FMDatabaseQueue databaseQueueWithPath:docDir];
        if (!isExist) {
            [dao createChannelTable];
        }
    });
    return dao;
}

- (BOOL)saveTODB:(NSArray *)channelArray {
    
    __block BOOL result = YES;
    static NSString *sql = @"INSERT OR IGNORE INTO channel_tab (channel_id, name, abbr_en, name_en, seq_id) VALUES \
                                (:channel_id, :name, :abbr_en, :name_en, :seq_id) ";
    [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        for (DFChannel *channel in channelArray) {
            
            NSDictionary *dict = [channel getDBParameter];
            
            result = [db executeUpdate:sql withParameterDictionary:dict];
            if (!result) {
                *rollback = YES;
                break;
            }
        }
    }];
    
    return result;
}

- (NSArray *)loadChannelArrayFromDB {
    
    NSMutableArray *array = [NSMutableArray array];
    static NSString *sql = @"SELECT channel_id, name, abbr_en, name_en, seq_id FROM channel_tab ";
    [self.queue inDatabase:^(FMDatabase *db) {
        FMResultSet *set = [db executeQuery:sql];
        while ([set next]) {
            [array addObject:[DFChannel initWithDictionary:[set resultDictionary]]];
        }
    }];
    
    return array;
}


#pragma mark - db option

- (BOOL)createChannelTable {
    NSString *sql = @"CREATE TABLE channel_tab (\
                        channel_id CHAR(256) PRIMARY KEY,\
                        name CHAR(256),\
                        abbr_en CHAR(256),\
                        name_en CHAR(256),\
                        seq_id INT);";
    __block BOOL execute = YES;
    [self.queue inDatabase:^(FMDatabase *db) {
        execute = [db executeUpdate:sql];
    }];
    if (execute) {
        NSLog(@"%s", __func__);
    }
    return execute;
}

@end
